package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.sercice.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private UserService userService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        //获取当前用户id
        Long userId = BaseContext.getId();
        //查询当前用户购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
        //判断一下购物车是否有数据  如果没有  就没法下单
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车为空,不能下单");
        }
        //查询用户数据
        User user = userService.getById(userId);
        //查询地址数据
        //从订单表中获取地址id
        Long addressBookId = orders.getAddressBookId();
        //查询到地址信息
        AddressBook addressBook = addressBookService.getById(addressBookId);
        //判断一下地址信息是否为空
        if (addressBook == null) {
            throw new CustomException("地址信息有误,不能下单");
        }

        Long orderId = IdWorker.getId();//订单号

        BigDecimal amount = new BigDecimal(0);

        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();

            BeanUtil.copyProperties(shoppingCart, orderDetail);

            orderDetail.setOrderId(orderId);

            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount = amount.add(orderDetail.getAmount());
            //向订单明细表添加数据  多条
            orderDetailService.save(orderDetail);
        }
        orders.setNumber(orderId.toString());
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(amount);
        orders.setUserId(userId);
        orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? " " : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? " " : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? " " : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? " " : addressBook.getDetail()));
        //向订单表添加数据  一条数据
        ordersService.save(orders);

        //清空购物车数据
        shoppingCartService.remove(wrapper);

        return R.success(null);
    }

    //手机端分页查询订单
    @GetMapping("/userPage")
    public R page(Integer page, Integer pageSize) {
        Long userId = BaseContext.getId();
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, userId);
        wrapper.orderByDesc(Orders::getOrderTime);

        List<Orders> ordersList = ordersService.list(wrapper);

        List<OrdersDto> ordersDtos = new ArrayList<>();

        //遍历订单集合 获取没一个订单信息
        for (Orders order : ordersList) {
            //获取每个订单的id
            Long orderId = order.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId, orderId);
            //一个订单内的菜品集合
            List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
            //创建一个ordersDto对象
            OrdersDto ordersDto = new OrdersDto();
            //把一个订单的菜品集合 copy给 ordersDto对象
            BeanUtil.copyProperties(order, ordersDto);
            //
            ordersDto.setOrderDetails(orderDetailList);

            ordersDtos.add(ordersDto);

        }
        //ordersService.page(pageInfo);
        long total = pageInfo.getTotal();
        Map map = new HashMap();
        map.put("records", ordersDtos);
        map.put("total", total);

        return R.success(map);

    }
/*

    // pc端分页查询
    @GetMapping("/page")
    public R pagePC(Integer page, Integer pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo, wrapper);
        return R.success(pageInfo);

    }
*/

    // pc端分页条件查询
    @GetMapping("/page")
    public R pagePC(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        //构建分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        //模糊查询  根据订单号查询
        wrapper.like(number != null, Orders::getId, number);
        ////模糊查询  根据时间查询
        wrapper.between(beginTime != null && endTime != null, Orders::getOrderTime, beginTime, endTime);
        //排序
        wrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo, wrapper);

        return R.success(pageInfo);

    }

    //订单派送接口

    @PutMapping
    public R ps(@RequestBody Orders orders) {
        //获取前台传过来的id
        Long ordersId = orders.getId();
        //获取订单状态
        Integer status = orders.getStatus();
        //根据前台传的id 获取表中订单的所有信息
        Orders order = ordersService.getById(ordersId);
        //修改状态
        order.setStatus(status);
        ordersService.updateById(order);

        return R.success("修改成功");
    }

    //再来一单
    @PostMapping("/again")
    public R again(@RequestBody Orders orders) {
        Long orderId = orders.getId();
        Orders order = ordersService.getById(orderId);
        Long userId = order.getUserId();
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(wrapper);
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail detail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtil.copyProperties(detail, shoppingCart);

            shoppingCart.setUserId(userId);
            shoppingCarts.add(shoppingCart);

        }
        shoppingCartService.saveBatch(shoppingCarts);

        return R.success(null);
    }

}
